const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const config = require('./database-config.js');

// 映射：CSV列顺序 → 槽位编号
// CSV顺序: 头盔, 项链, 武器, 护腕, 铠甲, 战靴
const slotNumByHeader = { '头盔': 1, '项链': 4, '武器': 2, '护腕': 5, '铠甲': 3, '战靴': 6 };
const headersInOrder = ['头盔', '项链', '武器', '护腕', '铠甲', '战靴'];

// 清洗 CSV 行
function parseCsv(filePath) {
    const raw = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
    const rows = [];
    for (const line of raw) {
        if (!line || /^\s*$/.test(line)) continue;
        const cols = line.split(',');
        // 期待列 >= 8: 宝石, 宝石属性, 6槽位, 最大加成
        if (cols.length < 8) continue;
        const gemNameCell = cols[0].trim();
        if (!gemNameCell || gemNameCell === '宝石' || gemNameCell.startsWith('备注')) continue;
        const attrName = cols[1].trim();
        const slotMarks = cols.slice(2, 8); // 6 槽位列
        const maxStr = cols[8] ? cols[8].trim() : '';

        // 支持多宝石：以中文顿号 '、' 分割
        const gemNames = gemNameCell.split('、').map(s => s.trim()).filter(Boolean);
        for (const gemName of gemNames) {
            rows.push({ gemName, attrName, slotMarks, maxStr });
        }
    }
    return rows;
}

function computeSlotsFromMarks(slotMarks) {
    const slots = [];
    for (let i = 0; i < headersInOrder.length; i++) {
        const head = headersInOrder[i];
        const mark = (slotMarks[i] || '').trim();
        if (mark) slots.push(slotNumByHeader[head]);
    }
    // 去重并排序
    return Array.from(new Set(slots)).sort((a, b) => a - b);
}

async function main() {
    const csvPath = path.resolve(__dirname, 'output/宝石说明.csv');
    if (!fs.existsSync(csvPath)) {
        console.error('❌ 找不到 CSV 文件:', csvPath);
        process.exit(1);
    }

    const rows = parseCsv(csvPath);
    console.log(`🔍 解析到 ${rows.length} 条 CSV 行（按宝石×属性展平）`);

    const conn = await mysql.createConnection(config.source);
    try {
        let updateCount = 0;
        for (const row of rows) {
            const slots = computeSlotsFromMarks(row.slotMarks);
            if (row.attrName === '穿透率') {
                // 移除护腕(5)、战靴(6)
                const filt = slots.filter((s) => s !== 5 && s !== 6);
                // 若 CSV 未显式包含武器且规则允许，可根据业务补充；这里保持 CSV 为准，不做自动补充
                row._slots = filt;
            } else {
                row._slots = slots;
            }

            const eqStr = row._slots.join(',');
            // 查找 gem_id
            const [gemRows] = await conn.execute(
                'SELECT id FROM gem_base WHERE name = ? LIMIT 1',
                [row.gemName]
            );
            if (!gemRows || gemRows.length === 0) {
                console.warn(`⚠️ 未找到宝石名称: ${row.gemName}`);
                continue;
            }
            const gemId = gemRows[0].id;

            // 更新匹配的属性记录（同名属性）
            const [attrRows] = await conn.execute(
                'SELECT id, equipment_slots FROM gem_attributes WHERE gem_id = ? AND attribute_name = ? LIMIT 1',
                [gemId, row.attrName]
            );
            if (!attrRows || attrRows.length === 0) {
                console.warn(`⚠️ 未找到属性记录: gem=${row.gemName}, attr=${row.attrName}`);
                continue;
            }
            const rec = attrRows[0];
            if (rec.equipment_slots !== eqStr) {
                await conn.execute(
                    'UPDATE gem_attributes SET equipment_slots = ?, updated_at = NOW() WHERE id = ?',
                    [eqStr, rec.id]
                );
                console.log(`✅ 更新 ${row.gemName} - ${row.attrName}: ${rec.equipment_slots} -> ${eqStr}`);
                updateCount++;
            } else {
                // console.log(`= 已匹配 ${row.gemName} - ${row.attrName}: ${eqStr}`);
            }
        }
        console.log(`\n🎉 完成更新，合计修改 ${updateCount} 条记录`);
    } finally {
        await conn.end();
    }
}

if (require.main === module) {
    main()
        .then(() => process.exit(0))
        .catch((err) => {
            console.error('❌ 执行失败:', err?.message || err);
            process.exit(1);
        });
}


